import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class TreeWidgetDemo(QWidget):
    def __init__(self,parent=None):
        super(TreeWidgetDemo,self).__init__(parent)
        self.setWindowTitle('treeWdiget案例')
        layout=QHBoxLayout()
        addbtn=QPushButton("添加")
        updatebtn=QPushButton("修改")
        delbtn=QPushButton("删除")
        layout.addWidget(addbtn)
        layout.addWidget(updatebtn)
        layout.addWidget(delbtn)
        addbtn.clicked.connect(self.addtreeNode)
        updatebtn.clicked.connect(self.updateNode)
        delbtn.clicked.connect(self.delNode)
        self.tree=QTreeWidget(self)
        #设置列数
        self.tree.setColumnCount(2)
        #设置标题
        self.tree.setHeaderLabels(['key','value'])
        #设置根节点
        root=QTreeWidgetItem(self.tree)
        root.setText(0,"root")
        root.setIcon(0,QIcon('panda.jpg'))
        #设置列宽
        self.tree.setColumnWidth(0,160)
        child1=QTreeWidgetItem(root)
        child1.setText(0,'child1')
        child1.setText(1,'python')

        child2 = QTreeWidgetItem(root)
        child2.setText(0, 'child2')
        child2.setText(1, 'java')

        child3 = QTreeWidgetItem(root)
        child3.setText(0, 'child3')
        child3.setText(1, 'js')

        child4 = QTreeWidgetItem(child3)
        child4.setText(0, 'child4')
        child4.setText(1, '4')

        child5 = QTreeWidgetItem(child3)
        child5.setText(0, 'child5')
        child5.setText(1, '5')
        self.tree.addTopLevelItem(root)
        self.tree.clicked.connect(self.onTreeClicked)
        #全部展开
        mainlayout=QVBoxLayout(self)
        mainlayout.addLayout(layout)
        mainlayout.addWidget(self.tree)
        self.setLayout(mainlayout)
    def onTreeClicked(self,index):
        item=self.tree.currentItem()
        print("key=%s ,value=%s" %(item.text(0),item.text(1)))

    def addtreeNode(self):
        item=self.tree.currentItem()
        node=QTreeWidgetItem(item)
        node.setText(0,"newnode")
        node.setText(1,'2')
    def updateNode(self):
        item=self.tree.currentItem()
        item.setText(0,"updatenode")
        item.setText(1,'20')

    def delNode(self):
        item = self.tree.currentItem()
        root=self.tree.invisibleRootItem()
        for item in  self.tree.selectedItems():
            (item.parent() or root).removeChild(item)

if __name__ == '__main__':
    app=QApplication(sys.argv)
    tree=TreeWidgetDemo()
    tree.show()
    sys.exit(app.exec_())
